import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const express = require('express')
const userRouter = express.Router()
import { mysqlObj } from '../../utils/mysql.js'
import { export_state } from '../../utils/state.js'

userRouter.get('/', function (req, res) {
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    res.write("<p>用户首页</p>")
    res.end()
})

userRouter.get('/root', function (req, res) {
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    res.write("超级用户首页")
})

/**
 * 公共接口（管理员、普通员工)
 */
userRouter.get('/getAuthorization', function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
    let openid = req.query.openid;
    mysqlObj.create().then((connect) => {

        connect.query(`select * from users where open_id='${openid}'`, function (error, results, fields) {
            if (error) throw error;

            if (results.valueOf().toString() == "") {
                res.write("<p>没有管理员权限！</p>")
                res.end()
            } else {

                // 返回查到的权限数据包
                res.write(JSON.stringify(results))
                res.end()
            }
        })

    })


})
/**
 * 普通员工api
 */
// 普通员工根目录


userRouter.get('/employee', function (req, res) {
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    res.write("普通员工首页")
    res.end()
})

/**
 * 插入普通员工的账号信息(username、phoneNumber、password)
 */
userRouter.get("/employee/insertAccount", function (req, res) {

    let username = req.query.username;
    let password = req.query.password;
    let phoneNumber = req.query.phoneNumber;

    mysqlObj.create().then((connect) => {

        let state = `insert into users(username, password, phone_number) values('${username}','${password}','${phoneNumber}')`;
        console.log(state, 'sdf')
        connect.query(state, function (error, results, fields) {
            console.log(results, "results")
        })
    })
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    res.write("插入普通员工账号信息")
    res.end()
})
// 登录验证，用户登录，插入用户账号和密码
userRouter.get('/employee/login', function (req, res) {

    let username = req.query.username;
    let password = req.query.password;

    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    mysqlObj.create().then((conn) => {
        let state = `select username,password from users where username='${username}' and password='${password}'`;
        conn.query(state, function (error, results, fields) {
            if (error) throw error;
            res.write(JSON.stringify(results))
            res.end()

        })
    })
})

// 执行插入/更新雇员的open_id,raw_data字段到数据库,承接上一步的/employee/login
userRouter.get("/employee/insertEmployee", function (req, res) {


    let rawData = req.query.rawData;
    let open_id = req.query.openid;
    let username = req.query.username;
    let password = req.query.password;
    // let state1 = export_state.queryState;
    mysqlObj.create().then((connect) => {

        res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })

        res.write("插入普通员工")
        let state = `update users set raw_data='${rawData}',open_id='${open_id}' where username='${username}' and password='${password}'`;
        console.log(state, 'state')
        connect.query(state, function (error, results, fields) {
            if (error) throw error;
            res.end()
        })

    })
})
// 根据openid查询用户信息
userRouter.get('/employee/getUserRawData', function (req, res) {
    res.writeHead(200, { "Content-type": "text/html; charset=utf-8" })
    let open_id = req.query.open_id
    mysqlObj.create().then((conn) => {
        conn.query(`select raw_data from users where open_id='${open_id}'`, function (error, results, fields) {
            if (error) throw error;
            res.write(JSON.stringify(results))
            res.end();
        })
    })
})
// 查询openid
userRouter.get('/employee/query', function (req, res) {


    // 未发生异常时执行
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })

    let openid = req.query.openid;
    try {

        let state = export_state.selectState({
            "table": "users",
            "keys": ["username", "password"]
        })
        mysqlObj.create().then((connect) => {
            // 连接成功后执行语句
            connect.query(`${state} where open_id='${openid}'`, function (error, results, fields) {
                if (error) throw error;

                if (results.valueOf().toString() == "") {
                    res.end("查询不到open_id");
                } else {
                    // 把username和password返回给前端
                    res.end(JSON.stringify(results[0]));
                }
            })
        })

    } catch (err) {
        console.log("错误为:", err)
        res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
        res.write(err.toString())
        res.end()
    }

})

// 执行mysql语句
userRouter.get('/employee/execute', function (req, res) {


    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })

    let state = req.query.state;
    mysqlObj.getConnection().then((connect) => {
        connect.query(state, function (error, results, fields) {
            if (error) throw error;
            console.log("成功执行execute接口的mysql语句！")
            res.end(JSON.stringify(results));
        })
    })
})
// 接收message, 用户登录后判断有没有信息没被发送到小程序端
userRouter.get('/employee/receiveMessage', function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
})
// 更新message, 用户登录后判断有没有信息没被发送到小程序端
userRouter.get('/employee/updateMessage', function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })

    // 要更新的open_id
    let open_id = req.query.open_id;

    // 是否有信息没发送
    let isSendMessage = false;
    // 数据库的查询结果
    let result;
    //查找数据库中该open_id的还没有发送过去的信息
    mysqlObj.create().then((conn) => {
        conn.query(`select * from messages_temp where open_id='${open_id}'`, function (error, results, field) {
            if (error) throw error;
            //找到到信息后返回
            if (JSON.stringify(results) == "[]") {
                isSendMessage = false;
            } else {
                isSendMessage = true;
                result = results;
            }
            console.log(results, 'fs')
        })


        // 等待然后返回查到的数据
        setTimeout(() => {
            if (isSendMessage == true) {
                // let date = new Date();
                // let timestamp = { "timestamp": date.getTime() };
                // result.unshift(timestamp);
                console.log("发送成功!")
                res.write(JSON.stringify(result));
            } else {
                // let timestamp = {"timestamp": ""};
                // result.unshift(timestamp);
                console.log("没有信息可发送!")
                res.write(JSON.stringify(result));
            }
            res.end();
        }, 400)
    })
})

// 确认message,把确认信息发送回来
userRouter.get('/employee/confirmUpdateMessage', function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })

    // 要确认的open_id
    let open_id = req.query.open_id;
    //删除数据库中该open_id的发送过去的信息
    mysqlObj.create().then((conn) => {
        conn.query(`delete from messages_temp where open_id='${open_id}'`, function (error, results, field) {
            if (error) throw error;
            console.log(`删除message缓存信息成功！`);
        })
    })
})


// 接收message,

// 更新message, 用户登录后判断有没有信息没被发送到小程序端
userRouter.get('/employee/updateCommunicate', function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })

    // 要更新的open_id
    let open_id = req.query.open_id;

    // 是否有信息没发送
    let isSendMessage = false;
    // 数据库的查询结果
    let result;
    //查找数据库中该open_id的还没有发送过去的信息
    mysqlObj.create().then((conn) => {
        conn.query(`select * from messages_temp where open_id='${open_id}'`, function (error, results, field) {
            if (error) throw error;
            //找到到信息后返回
            if (JSON.stringify(results) == "[]") {
                isSendMessage = false;
            } else {
                isSendMessage = true;
                result = results;
            }
            console.log(results, 'fs')
        })


        // 等待然后返回查到的数据
        setTimeout(() => {
            if (isSendMessage == true) {
                // let date = new Date();
                // let timestamp = { "timestamp": date.getTime() };
                // result.unshift(timestamp);
                console.log("发送成功!")
                res.write(JSON.stringify(result));
            } else {
                // let timestamp = {"timestamp": ""};
                // result.unshift(timestamp);
                console.log("没有信息可发送!")
                res.write(JSON.stringify(result));
            }
            res.end();
        }, 400)
    })
})

// 确认message,把确认信息发送回来
userRouter.get('/employee/confirmUpdateCommunicate', function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })

    // 要确认的open_id
    let open_id = req.query.open_id;
    //删除数据库中该open_id的发送过去的信息
    mysqlObj.create().then((conn) => {
        conn.query(`delete from messages_temp where open_id='${open_id}'`, function (error, results, field) {
            if (error) throw error;
            console.log(`删除message缓存信息成功！`);
        })
    })
})
// 查询员工信息
userRouter.get('/employee/getUserList', function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
    let username = req.query.username;
    let role = req.query.role;
    let isUsername = false;
    let isRole = false;
    Boolean(username) == true ? isUsername = true : isUsername = false
    Boolean(role) == true ? isRole = true : isRole = false


    mysqlObj.create().then((conn) => {

        conn.query(`select * from users`, function (error, results, field) {
            if (error) throw error;
            let json = {};
            json.list = results;
            res.write(JSON.stringify(json))
            res.end();
        })
    })
})

// 插入员工注册信息
userRouter.get("/employee/insertUser", function (req, res) {
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    mysqlObj.create().then((conn) => {
        conn.query('select * from users', function (error, results, field) {
            if (error) throw error;
            res.write()
            res.end()
        })
    })
})
// 删除员工注册信息

userRouter.get("/employee/insertUser", function (req, res) {
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    mysqlObj.create().then((conn) => {
        conn.query('select * from users', function (error, results, field) {
            if (error) throw error;
            res.write()
            res.end()
        })
    })
})
// 更新员工注册信息

userRouter.get("/employee/updateUser", function (req, res) {
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    mysqlObj.create().then((conn) => {
        conn.query('update users', function (error, results, field) {
            if (error) throw error;
            res.write()
            res.end()
        })
    })
})

export const user = userRouter;